package com.gem.taskplan.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gem.taskplan.service.CheckedNetWork;
import com.gem.taskplan.service.MySQLiteOpen;
import com.gem.taskplan.service.ReceiveMessageService;
import com.gem.taskplan.service.Register;
import com.gem.taskplan.service.SQLiteUtil;
import com.gem.taskplan.util.PropertiesUtil;
import com.gem.taskplan.util.SysApplication;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends FinalActivity {

	@ViewInject(id=R.id.uname,click="clearUname")AutoCompleteTextView uname;
	@ViewInject(id=R.id.upass,click="clearUpass")EditText upass;
	@ViewInject(id=R.id.bt_login,click="login")Button login;
	@ViewInject(id=R.id.bt_regist,click="register")Button register;
	@ViewInject(id=R.id.showPass,click="showPassWord")CheckBox showPass;
	@ViewInject(id=R.id.rememberPass,click="rememberPassWord")CheckBox rememberPass;

	private SharedPreferences sharedPreferences;
	private SharedPreferences.Editor editor;
	private String user_name,user_pass;
	private String[] DATA;
	private MySQLiteOpen open;
	private SQLiteUtil util;
	private List<Map<String, String>> list  = new ArrayList<Map<String,String>>();
	private long mExitTime;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);

		/***********退出程序************/
		SysApplication.getInstance().addActivity(this);

		init();//初始化代码  

		Intent intent = getIntent();
		if(intent!=null&&intent.getStringExtra("name")!=null){
			if(rememberPass.isChecked()){
				rememberPass.setChecked(false);
			}
			String name = intent.getStringExtra("name");
			uname.setText(name);
			upass.setText("");
		}


		/***************获取从上个界面传过来的值*****************/

		/*******************监听****************/
		uname.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			//监听提示条目的点击事件
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				TextView textView = (TextView) arg1.findViewById(R.id.text1);
				String name = textView.getText().toString();
				LoginActivity.this.uname.setText(name);
				System.out.println("选中了内容："+name);

				String uname1 =sharedPreferences.getString(name+"1", "");
				System.out.println("得到用户"+name+" = "+uname1 );
				if(uname1.length()!=0){
					LoginActivity.this.upass.setText(sharedPreferences.getString(uname1+"2", ""));
					System.out.println("该用户："+uname1+" 上次记住了密码,密码为："+sharedPreferences.getString(uname1+"2", ""));
					rememberPass.setChecked(true);
				}else {  
					System.out.println("该用户："+name+" 上次没记住了密码");
					LoginActivity.this.upass.setText("");
					rememberPass.setChecked(false);
				}
			}
		});
	}

	//登陆按钮跳转事件
	public void login(View v){

		/********************直接跳转到工作台界面（跳过了验证）**********************/
		/*Intent intent = new Intent(LoginActivity.this,TabHostActivity.class);
		System.out.println("已跳转到workTableActivity");
		startActivity(intent);*/


		user_name = uname.getText().toString();
		user_pass = upass.getText().toString();

		share();//判断是否记住密码
		String url = PropertiesUtil.getServerURL(this)+"/RegisterServlet";
		Register registers = new Register(this,url);
		if(registers.checkOut(user_name, user_pass)){
			registers.submitRequest(user_name, user_pass, "login");
		}

		open = new MySQLiteOpen(this, "user.db", 2);
		util = new SQLiteUtil(open.getReadableDatabase());
		boolean flag = util.check(user_name);
		util = new SQLiteUtil(open.getWritableDatabase());
		if(!flag){
			System.out.println("查询结果："+flag);
			util.insert(user_name, user_pass);
		}
	}

	//注册按钮跳转事件
	public void register(View v){
		Intent intent = new Intent(this,RegisterActivity.class);
		startActivityForResult(intent, 1);
		System.out.println("已跳转到RegisterActivity");
	}

	//注册跳转是有返回结果的跳转，故必须覆盖该方法获取返回的结果值
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==1&&resultCode==RESULT_OK){
			String nameBack = data.getStringExtra("userName");
			String passBack = data.getStringExtra("userPass");
			uname.setText(nameBack);
			upass.setText(passBack);
		}
	}

	public void clearUname(View v) {
//		uname.setText("");
//		upass.setText("");
		if(rememberPass.isChecked()){
			rememberPass.setChecked(false);
		}
		System.out.println("监听开始");
		refreshDATA();//点击文本刷新一次数据
	}

	//是否显示密码
	public void showPassWord(View view){
		if(showPass.isChecked()){ 
			//显示密码
			LoginActivity.this.upass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
		}else {
			//不显示密码
			LoginActivity.this.upass.setTransformationMethod(PasswordTransformationMethod.getInstance());
		}
	}

	//是否记住密码
	public void rememberPassWord(View view){
		share();
	}

	//初始化代码
	public void init(){
		sharedPreferences = getSharedPreferences("taskPlanShare", MODE_PRIVATE);
		editor = sharedPreferences.edit();

		uname.setText(sharedPreferences.getString(sharedPreferences.getString("lastUser", "")+"1", ""));
		upass.setText(sharedPreferences.getString(sharedPreferences.getString("lastUser", "")+"2", ""));
		//Toast.makeText(this, upass.getText().toString(), Toast.LENGTH_SHORT).show();
		if(upass.getText().toString().length()!=0){//如果此处读取密码不为空说明 记住密码是选中状态
			rememberPass.setChecked(true);
		}
	}  

	//密码存储
	public void share(){
		editor.putString("lastUser", user_name);
		if(rememberPass.isChecked()){
			//将密码存贮在本地
			editor.putString(user_name+"1", uname.getText().toString());
			editor.putString(user_name+"2", upass.getText().toString());
			editor.commit();
		}else {  
			//将记住的密码从本地移除
			editor.remove(user_name+"1");
			editor.remove(user_name+"2");
			editor.commit();
		}
	}

	//刷新数据
	public void refreshDATA(){
		open = new MySQLiteOpen(this, "user.db", 2);		
		util = new SQLiteUtil(open.getWritableDatabase());
		DATA = util.query();
		List<Map<String, String>> newlist = new ArrayList<Map<String,String>>();
		for(int i = 0;i<DATA.length;i++){
			HashMap< String, String> map = new HashMap<String, String>();
			map.put("name", DATA[i]);
			newlist.add(map);
			System.out.println("name  = "+DATA[i]);
		}
		list = newlist ;
		//写随笔提示代码段
		SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.login_1, new String[]{"name"}, new int[]{R.id.text1});
		this.uname.setAdapter(adapter);
	}

	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
			new AlertDialog.Builder(this).setTitle("您确定您要退出TaskPlan程序吗？").setIcon(R.drawable.taskplan2)
			.setPositiveButton("退出", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					System.exit(0);
					SysApplication.getInstance().exit(LoginActivity.this);
					Intent intent = new Intent(LoginActivity.this, ReceiveMessageService.class);
					// 停止推送服务
					stopService(intent);
					System.exit(0);
				}
			}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			}).create().show();
			
		}
		return super.onKeyDown(keyCode, event);
	}

}
